package com.gamex.findit.controller.api;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gamex.findit.ResultCode;
import com.gamex.findit.model.Member;
import com.gamex.findit.model.MemberItem;
import com.gamex.findit.model.MemberSkill;
import com.gamex.findit.service.MemberItemService;
import com.gamex.findit.service.MemberService;
import com.gamex.findit.service.MemberSkillService;
import com.gamex.findit.util.CommonUtil;
import com.gamex.findit.util.CryptoUtil;

@Controller("memberMember")
public class MemberController {
	
	private static final Logger logger = LoggerFactory.getLogger(MemberController.class);

	@Autowired MemberService memberService;
	@Autowired MemberItemService memberItemService;
	@Autowired MemberSkillService memberSkillService;
	
	/**
	 * @param request
	 * @param response
	 * @param model
	 * @param member
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/app/member/join.*")
	public ResponseEntity<String> join( HttpServletRequest request
			  		  , HttpServletResponse response
			  		  , Model model
			  		  , @ModelAttribute Member member) throws Exception{
		
		HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "application/json; charset=utf-8");
        
		ModelMap body = new ModelMap();
		if(StringUtils.isEmpty(member.getUserId()) || StringUtils.isEmpty(member.getUserPass()) 
		  || StringUtils.isEmpty(member.getUserDevice())|| StringUtils.isEmpty(member.getUserCharacter())){
				body.addAttribute(ResultCode.RESULT,ResultCode.RESULT_CODE_FAIL);
		}else{
			int result = 0;
			member.setUserPass(CryptoUtil.getEncryptedPassword(member.getUserPass()));
			
			try {
				result = memberService.insertMember(member);
			} catch (Exception e) {
				body.addAttribute(ResultCode.RESULT,ResultCode.RESULT_CODE_FAIL);
			}
			
			if(result == 1){
			   //resultValue= getProcessService().selectImage(userId, userDevice);
				//body.addAttribute("images","");
				//body.addAttribute("count",0);
				body.addAttribute(ResultCode.RESULT,ResultCode.RESULT_CODE_SUCCESS);
			}else{
				body.addAttribute(ResultCode.RESULT,ResultCode.RESULT_CODE_FAIL);
			}
		}
			return new ResponseEntity<String>(CommonUtil.toJson(body), responseHeaders, HttpStatus.CREATED);
	}
	
	/**
	 * @param request
	 * @param response
	 * @param model
	 * @param member
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/app/member/login.*")
	public ResponseEntity<String>  login(HttpServletRequest request
			  		  , HttpServletResponse response
			  		  , ModelMap model
			  		  , @ModelAttribute Member member) throws Exception{
		
		HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "application/json; charset=utf-8");
        
		ModelMap body = new ModelMap();
		String password = member.getUserPass();
		String cryptedPassword = null;
		Member result = null;
		
		try {
			result = memberService.getMemberView(member.getUserId());
			
		} catch (Exception e) {
			body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
		}
		
		if(result != null && StringUtils.isNotEmpty(member.getUserId()) && StringUtils.isNotEmpty(password)){
			cryptedPassword = CryptoUtil.getEncryptedPassword(password);
			
			if(result.getUserPass().equals(cryptedPassword)){
				//resultValue= getProcessService().selectImage(userId, userDevice);
				//body.addAttribute("images", "");
				//body.addAttribute("count", 0);
				
				MemberItem item = new MemberItem();
				item.setUserId(member.getUserId());
				List<MemberItem> items = memberItemService.getMemberItem(item);
				
				MemberSkill skill = new MemberSkill();
				skill.setUserId(member.getUserId());
				List<MemberSkill> skills = memberSkillService.getMemberSkill(skill);
				
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_SUCCESS);
				body.addAttribute("user", result);
				body.addAttribute("item", items);
				body.addAttribute("skill", skills);
			}else{
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_NOT_MATCH);
			}
			
		}else{
			body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
		}

		return new ResponseEntity<String>(CommonUtil.toJson(body), responseHeaders, HttpStatus.CREATED);
	}
		
	/**
	 * @param request
	 * @param response
	 * @param model
	 * @param member
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/app/member/hasId.*")
	public ResponseEntity<String>  checkId( HttpServletRequest request
				  		 , HttpServletResponse response
				  		 , Model model
				  		 , @ModelAttribute Member member) throws Exception{
		
		HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "application/json; charset=utf-8");
        
		ModelMap body = new ModelMap();
		String userId = member.getUserId();
		
		if(StringUtils.isEmpty(userId)){
			body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
		}else{
			
			Member result = memberService.getMemberView(member.getUserId());
			if(result != null && StringUtils.isNotEmpty(result.getUserId())){
				body.addAttribute(ResultCode.RESULT,ResultCode.RESULT_CODE_SUCCESS);
			}else{
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
			}
		}
			return new ResponseEntity<String>(CommonUtil.toJson(body), responseHeaders, HttpStatus.CREATED);
	}
	
	/**
	 * @param request
	 * @param response
	 * @param model
	 * @param member
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/app/member/changeCharacter.*")
	public ResponseEntity<String>  changeChar( HttpServletRequest request
					  		, HttpServletResponse response
					  		, Model model
					  		, @ModelAttribute Member member) throws Exception{
		
		HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "application/json; charset=utf-8");
        
		ModelMap body = new ModelMap();
		
		if(StringUtils.isEmpty(member.getUserCharacter()) || StringUtils.isEmpty(member.getUserId())){
			body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
		}else{
			
			try {
				Member m = new Member();
				m.setUserCharacter(member.getUserCharacter());
				m.setUserId(member.getUserId());
				memberService.updateMember(m);
				body.addAttribute(ResultCode.RESULT,ResultCode.RESULT_CODE_SUCCESS);
			} catch (Exception e) {
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
			}
		}
			return new ResponseEntity<String>(CommonUtil.toJson(body), responseHeaders, HttpStatus.CREATED);
	}
	
	/**
	 * @param request
	 * @param response
	 * @param model
	 * @param member
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value ={"/app/member/addCoin.*", "/app/member/spendCoin.*"})
	public ResponseEntity<String> addCoin( HttpServletRequest request
				  		 , HttpServletResponse response
				  		 , Model model
				  		 , @ModelAttribute Member member) throws Exception{
		
		HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "application/json; charset=utf-8");
        
		ModelMap body = new ModelMap();
		if(member.getCoin() == 0 || StringUtils.isEmpty(member.getUserId())){
			body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
		}else{
			Member m = new Member();
			
			String path = request.getRequestURI();
			if(path.contains("add"))
				m.setOperation("+");
			else
				m.setOperation("-");
			
			try {
				m.setCoin(member.getCoin());
				m.setUserId(member.getUserId());
				memberService.updateMemberNumeric(m);
				body.addAttribute(ResultCode.RESULT,ResultCode.RESULT_CODE_SUCCESS);
			} catch (Exception e) {
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
			}
		}
			return new ResponseEntity<String>(CommonUtil.toJson(body), responseHeaders, HttpStatus.CREATED);
	}
	
	/**
	 * @param request
	 * @param response
	 * @param model
	 * @param member
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value ={"/app/member/addPoint.*", "/app/member/spendPoint.*"})
	public ResponseEntity<String> addPoint( HttpServletRequest request
				  		 , HttpServletResponse response
				  		 , Model model
				  		 , @ModelAttribute Member member) throws Exception{
		
		HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "application/json; charset=utf-8");
        
		ModelMap body = new ModelMap();
		if(member.getPoint() == 0 || StringUtils.isEmpty(member.getUserId())){
			body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
		}else{
			Member m = new Member();
			
			String path = request.getRequestURI();
			if(path.contains("add"))
				m.setOperation("+");
			else
				m.setOperation("-");
			
			try {
				m.setPoint(member.getPoint());
				m.setUserId(member.getUserId());
				memberService.updateMemberNumeric(m);
				body.addAttribute(ResultCode.RESULT,ResultCode.RESULT_CODE_SUCCESS);
			} catch (Exception e) {
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
			}
		}
			return new ResponseEntity<String>(CommonUtil.toJson(body), responseHeaders, HttpStatus.CREATED);
	}
	
	/**
	 * @param request
	 * @param response
	 * @param model
	 * @param member
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = {"/app/member/addScore.*", "/app/member/spendScore.*"})
	public ResponseEntity<String> addScore( HttpServletRequest request
				  		 , HttpServletResponse response
				  		 , Model model
				  		 , @ModelAttribute Member member) throws Exception{
		
		HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "application/json; charset=utf-8");
        
		ModelMap body = new ModelMap();
		if(member.getScore() == 0 || StringUtils.isEmpty(member.getUserId())){
			body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
		}else{
			Member m = new Member();
			
			String path = request.getRequestURI();
			if(path.contains("add"))
				m.setOperation("+");
			else
				m.setOperation("-");
			
			try {
				m.setScore(member.getScore());
				m.setUserId(member.getUserId());
				memberService.updateMemberNumeric(m);
				body.addAttribute(ResultCode.RESULT,ResultCode.RESULT_CODE_SUCCESS);
			} catch (Exception e) {
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
			}
		}
			return new ResponseEntity<String>(CommonUtil.toJson(body), responseHeaders, HttpStatus.CREATED);
	}
	
	/**
	 * @param request
	 * @param response
	 * @param model
	 * @param member
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = {"/app/member/ddLevel.*"})
	public ResponseEntity<String> addLevel( HttpServletRequest request
				  		 , HttpServletResponse response
				  		 , Model model
				  		 , @ModelAttribute Member member) throws Exception{
		
		HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "application/json; charset=utf-8");
        
		ModelMap body = new ModelMap();
		if(member.getLevel()  == 0  || StringUtils.isEmpty(member.getUserId())){
			body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
		}else{
			Member m = new Member();
			
			String path = request.getRequestURI();
			if(path.contains("add"))
				m.setOperation("+");
			else
				m.setOperation("-");
			
			try {
				m.setLevel(member.getLevel());
				m.setUserId(member.getUserId());
				memberService.updateMemberNumeric(m);
				body.addAttribute(ResultCode.RESULT,ResultCode.RESULT_CODE_SUCCESS);
			} catch (Exception e) {
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
			}
		}
			return new ResponseEntity<String>(CommonUtil.toJson(body), responseHeaders, HttpStatus.CREATED);
	}
	
	/**
	 * @param request
	 * @param response
	 * @param model
	 * @param member
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = {"/app/member/mutiAddUp.*"})
	public ResponseEntity<String> mutiAddUp( HttpServletRequest request
				  		 , HttpServletResponse response
				  		 , Model model
				  		 , @ModelAttribute Member member) throws Exception{
		
		HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "application/json; charset=utf-8");
        
		ModelMap body = new ModelMap();
		if(!StringUtils.isEmpty(member.getUserId())){
			member.setOperation("+");
			
			try {
				System.out.println(member.toString());
				memberService.updateMemberNumeric(member);
				body.addAttribute(ResultCode.RESULT,ResultCode.RESULT_CODE_SUCCESS);
			} catch (Exception e) {
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
			}
		}
		
		return new ResponseEntity<String>(CommonUtil.toJson(body), responseHeaders, HttpStatus.CREATED);
	}
	
	/**
	 * @param request
	 * @param response
	 * @param model
	 * @param member
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/app/member/cancelAccount.*")
	public ResponseEntity<String> cancelAccount( HttpServletRequest request
				  		 , HttpServletResponse response
				  		 , Model model
				  		 , @ModelAttribute Member member) throws Exception{
		
		HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "application/json; charset=utf-8");
        
		ModelMap body = new ModelMap();
		String userId = member.getUserId();
		
		if(StringUtils.isEmpty(userId) || StringUtils.isEmpty(member.getUserPass())){
			body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
		}else{
			 member.setUserPass(CryptoUtil.getEncryptedPassword(member.getUserPass()));
			 memberService.deleteMember(member);
			 // memberItem delete
			 // memberSkill delete
			 // friend delete
			 body.addAttribute(ResultCode.RESULT,ResultCode.RESULT_CODE_SUCCESS);
		}
			return new ResponseEntity<String>(CommonUtil.toJson(body), responseHeaders, HttpStatus.CREATED);
		}
	
}
